package com.white.algebra.controller;

import com.google.gson.Gson;
import com.white.algebra.dao.PermissionDao;
import com.white.algebra.dao.RoleDao;
import com.white.algebra.dao.impl.PermissionDaoImpl;
import com.white.algebra.dao.impl.RoleDaoImpl;
import com.white.algebra.domain.Permission;
import com.white.algebra.domain.Power;
import com.white.algebra.domain.Role;
import com.white.algebra.domain.UserInfo;
import com.white.algebra.service.UserService;
import com.white.algebra.service.impl.UserServiceImpl;
import com.white.algebra.utils.PasswordEncoderUtils;
import com.white.algebra.utils.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserController extends BaseServlet{
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // cookie登录
        req.setCharacterEncoding("utf-8");
        Cookie[] cookies = req.getCookies();
        String rememberUserName = null;
        String rememberUserPwd = null;
        for(Cookie cookie :cookies){
            if("userCookie".equals(cookie.getName())){
                rememberUserName = cookie.getValue().split("&")[0];
                rememberUserPwd = cookie.getValue().split("&")[1];
            }
        }
        if(rememberUserName==null||rememberUserPwd==null){
            String username=req.getParameter("username");
            if(username==null){
                resp.sendRedirect(req.getContextPath()+"/login.jsp");
                return;
            }
        }else{
            UserService userService=new UserServiceImpl();
            UserInfo userInfo=userService.login(rememberUserName,rememberUserPwd);
            req.getSession().setAttribute("user",userInfo);
            //取出用户拥有的所有权限
            //权限设置
            ArrayList<String> arrayList=userService.getAllPermission(userInfo.getId());
            Power power=WebUtils.powerUtil(arrayList);
            req.getSession().setAttribute("power",power);

            if (userInfo!=null){
                req.getRequestDispatcher("/pages/main.jsp").forward(req,resp);
                return;
            }else {
                resp.sendRedirect(req.getContextPath()+"/login.jsp");
                return;
            }
        }

        String username=req.getParameter("username");
        String password=req.getParameter("password");
        password= PasswordEncoderUtils.getMd5(password);
        UserService userService=new UserServiceImpl();
        UserInfo userInfo=userService.login(username,password);
        req.getSession().setAttribute("user",userInfo);
        //权限设置
        ArrayList<String> arrayList=userService.getAllPermission(userInfo.getId());
        Power power=WebUtils.powerUtil(arrayList);
        req.getSession().setAttribute("power",power);

        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        if (userInfo!=null){
            String isPwdRemember = req.getParameter("isPwdRemember");
            if((isPwdRemember!=null)&&(isPwdRemember.equals("on"))){
                Cookie cookie = new Cookie("userCookie", username+"&"+password);
                // 有效期,秒为单位,7天
                cookie.setMaxAge(604800);
                resp.addCookie(cookie);
            }
            req.getRequestDispatcher("/pages/main.jsp").forward(req,resp);
            return;
        }else {
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }
    }
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String email=req.getParameter("email");
        password= PasswordEncoderUtils.getMd5(password);
        UserService userService=new UserServiceImpl();
        userService.register(username,password,email);
        resp.sendRedirect(req.getContextPath()+"/login.jsp");
    }
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().invalidate();
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie: cookies) {
            if ("userCookie".equals(cookie.getName())) {
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
        }
        resp.sendRedirect(req.getContextPath());
    }
    protected void code(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String verifyCode = req.getParameter("code");
        String kaptchaValue = (String) req.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        Map<String,String> map=new HashMap<>();
        if(kaptchaValue == null || kaptchaValue == ""||!verifyCode.equalsIgnoreCase(kaptchaValue)) {
            map.put("result","f");
        }else {
            map.put("result","t");
        }
        Gson gson=new Gson();
        //转换成json
        String json=gson.toJson(map);
        resp.getWriter().write(json);
    }


}
